package com.iwop.moto.controller.weixin;

import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.controller.BaseController;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.stringUtil.DateFormatter;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.iwop.moto.utils.weixin.WeixinUtil;
import com.iwop.moto.utils.weixin.model.WxPayDto;
import com.iwop.moto.utils.weixin.utils.WxPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


/**
 * @功能: 微信业务模块管理
 * @创建: liuwb 2016-08-16 10:13 by Create
 * @说明: 微信号[开摩邦网]业务模块管理
 */
@Controller
public class WxMotoController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private IDataService dataService;

    @Autowired
    private AuditHistoryService auditHistoryService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private WxPayService wxPayService;

    /** ----------------------------------------------------------------------------------------------------**/
    /** **************************************** Star 微信认证处理模块 Star  ******************************* **/
    /** ----------------------------------------------------------------------------------------------------**/

    /**
     * @param response
     * @throws Exception
     * @功能: 微信获取openid与用户授权信息
     * @日期: liuwb 2016-08-16 19:20 by create
     * @说明: return_url 微信返回的回调方法
     */
    @RequestMapping("/api/wx/oauth2/authorize")
    public void apiWxoOauth2Authorize(HttpServletResponse response) throws Exception {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            WeixinUtil.Oauth2Authorize(response, Comm.WX_RETURN_URL, SRModel.getString("reqUrl"));
        } catch (Exception e) {
            log.error("", e);
            e.printStackTrace();
        }
    }

    /**
     * @return jsonString
     * @功能: 微信获取用户信息 - 回调函数
     * @日期: liuwb 2016-08-16 19:22 by create
     * @说明: 根据code获取accessToken 授权获取用户信息
     */
    @RequestMapping("/api/wx/authorize/result")
    public void apiWxAuthorizeResult(HttpServletResponse response) {
        SuperRecordModel SRModel = this.getSRModel();
        String reqUrl = SRModel.getString("state");
        try {
            SuperRecordModel attribute = (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
            if(null==attribute){
                String code = SRModel.getString("code");
                Long tokenTime = System.currentTimeMillis();
                SRModel = WeixinUtil.Oauth2AccessToken(code);// 获取openid、access_token
                SuperRecordModel wxInfoSrm = WeixinUtil.snsUserInfo(SRModel.getString("openid"),
                        SRModel.getString("access_token"));
                wxInfoSrm.put("scope", SRModel.getString("scope"));
                wxInfoSrm.put("expires_in", SRModel.get("expires_in"));
                wxInfoSrm.put("access_token", SRModel.getString("access_token"));
                wxInfoSrm.put("refresh_token", SRModel.getString("refresh_token"));
                wxInfoSrm.put("token_time", tokenTime + (((Integer) SRModel.get("expires_in") / 2) * 1000));
                SRModel.put("wx_open_id", SRModel.getString("openid"));
                SRModel.put("user_type", "5");//服务商
                SuperRecordModel userInfo = userService.findUserByOpenId(SRModel);
                if (userInfo != null && userInfo.size() > 0) {//服务商
                    getSession().setAttribute(Comm.SESSION_USER, userInfo);
                    getSession().setAttribute("isService", true);
                }
                getSession().setAttribute(Comm.SESSION_WEIXIN_ID, wxInfoSrm);//微信用户信息
            }
            response.sendRedirect(reqUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @功能: 微信刷新access_token
     * @日期: liuwb 2016-08-17 09:12 by create
     * @说明: 由于access_token拥有较短的有效期，当access_token超时后，可以使用refresh_token进行刷新，
     * refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权。
     */
    @RequestMapping("/api/wx/refresh/token")
    @ResponseBody
    public ResultModel apiWxRefreshToken() {
        SuperRecordModel SRModel = this.getSRModel();
        try {
            String refreshToken = SRModel.getString("refresh_token");
            Long tokenTime = new Date().getTime();
            SRModel = WeixinUtil.Oauth2RefreshToken(refreshToken);
            SRModel.put("token_time", tokenTime);
            return getSucceed(SRModel);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @功能: 微信服务端(开发模式)认证Url
     * @日期: liuwb by 2016-09-12 on create
     * @说明: 微信平台管理 - (启用)服务器配置开启开发模式 / 事件回调访问函数
     */
    @RequestMapping("/api/wx/check/sign")
    @ResponseBody
    public void apiWxCheckSignature(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String openid = request.getParameter("openid");
        String echostr = request.getParameter("echostr");
        if (echostr != null) { /** 微信服务端认证Url **/
            PrintWriter out = response.getWriter();
            // 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (WeixinUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
            out.close();
            out = null;
        } else {
            WeixinUtil.Oauth2Authorize(response, Comm.WX_RETURN_URL, "api/wx/user/members/center");
            System.out.println(openid);
        }
    }

    /******************************************* End 微信认证处理模块 End  ************************************/
    /** ----------------------------------------------------------------------------------------------------**/
    /****************************************  Star 微信摩邦平台审核 Star  ************************************/
    /**
     * @功能: 平台审核管理模块
     * @日期: liuwb on 2016-09-17 14:18 by create
     */
    @RequestMapping(value = "/api/wx/kmb/audit/center")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditCenter() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            srm.put("adminAuditCount", userService.findAdminAduitCount());
            srm.put("serviceAuditCount", userService.findServiceAduitCount());
            srm.put("adminHistoryCount", userService.findAdminAduitHistoryCount());
            mv.addObject("srm", srm);
            mv.setViewName("weixin/wx_audit_center");
            return mv;
        }
    }

    /**
     * @功能 微信后台 - 平台审核 - 列表
     * @日期 liuwb on 2016-08-30 17:14 by create
     */
    @RequestMapping(value = "/api/wx/kmb/audit/list")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditList(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        String sType = request.getParameter("s_type");
        if(StringUtils.isEmpty(sType)){
            sType="0";
        }
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            /** 获取审核服务商列表 **/
            srm.put("user_type", "5");//服务商
            srm.put("audit_flag", "0");//未审核
            List<SuperRecordModel> serviceList = userService.findAdminAuditList(srm);
            mv.addObject("serviceList", serviceList);
            /** 获取审核维修店列表 **/
            srm.put("user_type", "1");//维修店
            srm.put("audit_flag", "1");//服务商审核通过需平台审核
            List<SuperRecordModel> storeList = userService.findAdminAuditList(srm);
            mv.addObject("storeList", storeList);
            mv.addObject("s_type",sType);
            mv.setViewName("weixin/wx_audit_list");
            return mv;
        }
    }

    /**
     * @功能: 微信后台接口 - 平台审核成员 - 维修店 - 详情
     * @日期: liuwb on 2016-08-30 17:14 by create
     * @参数: userId 用户主键信息
     */
    @RequestMapping(value = "/api/wx/store/audit/detail")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditDetail() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        }
        mv.addObject("hostUser",promotionService.findHostUserInfo(srm.getString("userId")));
        srm = userService.findUserAndStoreByUserId(srm.getString("userId"));
        mv.addObject("srm", srm);
        mv.setViewName("weixin/wx_audit_store");
        return mv;
    }

    /**
     * @功能: 微信后台接口 - 平台审核成员 - 服务商 - 详情
     * @日期: liuwb on 2016-08-30 17:34 by create
     * @参数: userId 用户主键信息
     */
    @RequestMapping(value = "/api/wx/service/audit/detail")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbServiceDetail() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        }
        mv.addObject("hostUser",promotionService.findHostUserInfo(srm.getString("userId")));
        srm = userService.findUserBySid(srm);
        srm.put("addtime", srm.get("audit_time") == null ? "" : DateFormatter.simpleDateFormat((Date) srm.get("audit_time")));
        mv.addObject("srm", srm);
        SuperRecordModel tlParams = new SuperRecordModel();
        tlParams.put("user_id",srm.get("sid"));
        tlParams.put("pay_type","bargain");
        Long totalFee = wxPayService.findByParamsTotalFee(tlParams);
        mv.addObject("totalFee",totalFee);
        mv.setViewName("weixin/wx_audit_service");
        return mv;
    }

    /**
     * @功能: 微信后台接口 - 平台审核后台 - 服务商审核(状态) - 列表
     * @日期: liuwb on 2016-09-18 09:59 by create
     */
    @RequestMapping(value = "/api/wx/kmb/audit/service/list")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditServiceList() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            /** 获取所有服务商审核中维修店列表 **/
            srm.put("user_type", "1");//维修店
            srm.put("audit_flag", "0");//0维修店需服务商审核的
            List<SuperRecordModel> storeList = userService.findAdminAuditList(srm);
            mv.addObject("storeList", storeList);
            mv.setViewName("weixin/wx_audit_service_list");
            return mv;
        }
    }

    /**
     * @功能: 微信后台接口 - 平台审核后台 -平台审核历史 - 用户列表
     * @日期: liuwb on 2016-09-18 by create
     */
    @RequestMapping(value = "/api/wx/kmb/audit/history/list")
    @LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditHistoryList(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        String s_type = request.getParameter("s_type");
        if(StringUtils.isEmpty(s_type)){
            s_type="0";
        }
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            /** 获取平台审核服务商历史列表 **/
            srm.put("user_type", "5");//服务商
            srm.put("audit_flag", "AdminHistory");//平台审核历史: -2 不通过 或者 2 通过
            List<SuperRecordModel> serviceList = userService.findAdminAuditList(srm);
            String addTime="";
            Map<String ,Object> map=new LinkedHashMap<>();
            List<SuperRecordModel> list=new ArrayList<SuperRecordModel>();
            if(serviceList!=null&&serviceList.size()>0){
                for (SuperRecordModel srms:serviceList){
                    if(StringUtils.isEmpty(addTime)){
                        addTime = srms.getString("addtime");
                    }
                    if(addTime.equals(srms.getString("addtime"))){
                        list.add(srms);
                    }else {
                        map.put(addTime,list);
                        list=new ArrayList<>();
                        addTime=srms.getString("addtime");
                        list.add(srms);
                    }
                }
            }
            if(list.size()>0){
                map.put(addTime,list);
            }

            mv.addObject("serviceList", map);
            /** 获取平台审核维修店历史列表 **/
            srm.put("user_type", "1");//维修店
            srm.put("audit_flag", "AdminHistory");//平台审核历史 -2 不通过 或者 2 通过
            List<SuperRecordModel> storeList = userService.findAdminAuditList(srm);
            String addTimes="";
            Map<String ,Object> map1=new LinkedHashMap<>();
            List<SuperRecordModel> list1=new ArrayList<SuperRecordModel>();
            if(storeList!=null&&storeList.size()>0){
                for (SuperRecordModel srms:storeList){
                    if(StringUtils.isEmpty(addTimes)){
                        addTimes = srms.getString("addtime");
                    }
                    if(addTimes.equals(srms.getString("addtime"))){
                        list1.add(srms);
                    }else {
                        map1.put(addTimes,list1);
                        list1=new ArrayList<>();
                        addTimes=srms.getString("addtime");
                        list1.add(srms);
                    }
                }
            }
            if(list1.size()>0){
                map1.put(addTimes,list1);
            }
            mv.addObject("s_type",s_type);
            mv.addObject("storeList", map1);
            mv.setViewName("weixin/wx_audit_history_list");
            return mv;
        }
    }

    /**
     * 按照日期查询-平台审核后台 -平台审核历史 - 用户列表
     * */
    @RequestMapping(value = "/api/wx/count/user/people")
    @LoginAuth(isWx = true)
    public ModelAndView countWXPeople() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            mv.addObject("type","user");
            /** 获取平台审核服务商历史列表 **/
            if(!srm.containsKey("start_time")){
                mv.setViewName("weixin/wx_audit_query");
                mv.addObject("start_time","");
                mv.addObject("end_time","");
                return mv;
            }else {

            }
            srm.put("user_type", "5");//服务商
            srm.put("audit_flag", "AdminHistory");//平台审核历史: -2 不通过 或者 2 通过
            List<SuperRecordModel> serviceList = userService.findAdminAuditListFromDate(srm);
            int counts=0;
            if(serviceList!=null){
                counts = serviceList.size();
            }
            mv.addObject("countService",counts);
            mv.addObject("serviceList", serviceList);
            /** 获取平台审核维修店历史列表 **/
            mv.setViewName("weixin/wx_audit_query");
            return mv;
        }
    }

    @RequestMapping(value = "/api/wx/count/store/people")
    @LoginAuth(isWx = true)
    public ModelAndView countWXStorePeople() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        SuperRecordModel wxInfo = (SuperRecordModel) getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        srm.put("codetype", "AdminWxAudit");//F_DATA:字典类型
        srm.put("datavalue", wxInfo.getString("openid"));
        List<SuperRecordModel> AdminWxAuditList = dataService.findListByCodeType(srm);
        if (AdminWxAuditList == null || AdminWxAuditList.size() == 0) {
            mv.addObject("error_msg", ErrCode.NOT_VISIT_INVALID);
            mv.setViewName("error");
            return mv;
        } else {
            mv.addObject("type","store");
            int counts=0;
            /** 获取平台审核维修店历史列表 **/
            srm.put("user_type", "1");//维修店
            srm.put("audit_flag", "AdminHistory");//平台审核历史 -2 不通过 或者 2 通过
            if(!srm.containsKey("start_time")){
                mv.addObject("start_time","");
                mv.addObject("end_time","");
                mv.setViewName("weixin/wx_audit_query");
                return mv;
            }else {
                mv.addObject("start_time",srm.getString("start_time"));
                mv.addObject("end_time",srm.getString("end_time"));
            }
            List<SuperRecordModel> storeList = userService.findAdminAuditListFromDate(srm);
            if(storeList!=null){
                counts = storeList.size();
            }
            mv.addObject("countService",counts);
            mv.addObject("serviceList", storeList);
            mv.setViewName("weixin/wx_audit_query");
            return mv;
        }
    }

    /**
     * @功能: 微信后台接口 - 平台审核后台 -平台审核历史 - 流程记录
     * @日期: liuwb on 2016-10-08 by create
     */
    @RequestMapping(value = "/api/wx/kmb/audit/history")
    //@LoginAuth(isWx = true)
    public ModelAndView apiWxKmbAuditHistory() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        mv.addObject("isAuditFlag", srm.getString("isAuditFlag"));// 1: 审核 0 非审核
        List<SuperRecordModel> historys = auditHistoryService.findUserAuditHistory(srm);
        srm = userService.findUserBySid(srm);
        mv.addObject("srm", srm);
        mv.addObject("historys", historys);
        mv.setViewName("weixin/audit_history");
        return mv;
    }

    /**
     * @功能:微信扫码支付
     */
    @RequestMapping(value = "/api/wx/pay/qrcode")
    public ModelAndView payWxQrcode() {
        ModelAndView mv = new ModelAndView();
        SuperRecordModel srm = this.getSRModel();
        WxPayDto tpWxPay = new WxPayDto();
        String encoderImgId = SequenceUtil.Serial("MOBOM-");//订单号/二维码图片名称
        tpWxPay.setBody("测试");
        tpWxPay.setOrderId(encoderImgId);
        tpWxPay.setSpbillCreateIp("127.0.0.1");
        tpWxPay.setTotalFee("0.01");//测试金额0.01元
        String barCodeUrl = WxPayUtil.getCodeurl(tpWxPay);//发送请求
        mv.addObject("wxPayUrl", barCodeUrl);
        mv.setViewName("weixin/wx_pay_qrcode");
        return mv;
    }

}